<template>
  <div class="product_container">
    <!--    <div class="search_view">-->
    <!--      <el-input-->
    <!--        v-model="search_text"-->
    <!--        @input="debouncedSearch"-->
    <!--        placeholder="What are you looking for?">-->
    <!--        <template #prefix>-->
    <!--          <svg-->
    <!--            xmlns="http://www.w3.org/2000/svg"-->
    <!--            width="20"-->
    <!--            height="20"-->
    <!--            viewBox="0 0 20 20"-->
    <!--            fill="none">-->
    <!--            <path-->
    <!--              d="M9.58301 2.58203C13.4489 2.58203 16.5828 5.71619 16.583 9.58203C16.583 11.3512 15.9252 12.9659 14.8428 14.1982L18.4473 17.8027C18.7397 18.0957 18.74 18.5706 18.4473 18.8633C18.1545 19.1558 17.6796 19.1556 17.3867 18.8633L13.7383 15.2148C12.576 16.0736 11.139 16.582 9.58301 16.582C5.71716 16.5819 2.58301 13.4479 2.58301 9.58203C2.58318 5.7163 5.71727 2.58221 9.58301 2.58203ZM9.58301 4.08203C6.5457 4.08221 4.08318 6.54472 4.08301 9.58203C4.08301 12.6195 6.54559 15.0819 9.58301 15.082C12.6206 15.082 15.083 12.6196 15.083 9.58203C15.0828 6.54461 12.6205 4.08203 9.58301 4.08203Z"-->
    <!--              fill="#7A7A7A" />-->
    <!--          </svg>-->
    <!--        </template>-->
    <!--      </el-input>-->
    <!--    </div>-->
    <div class="content">
      <block v-if="customizationList?.length > 0">
        <div class="title ml-[24px] mb-[8px]">Print On Demand</div>
        <div class="cus_img_list pl-[24px]">
          <div
            v-for="item in customizationList"
            @click="goDetail(item)"
            :key="item.id"
            class="cus_item_view">
            <img class="cus_item_img" v-img-zoom :src="item.img" alt="" />
            <div class="name">
              {{ item.name }}
            </div>
          </div>
        </div>
      </block>
      <div class="title ml-[24px] mt-[24px]">Products</div>
      <productListV2
        :products="products"
        :loading="loading"
        :loadMoreLoading="loadMoreLoading"
        :hasMore="userInfo ? hasMore : true" />
    </div>
  </div>
</template>

<script setup lang="ts">
  import {
    computed,
    nextTick,
    onActivated,
    onDeactivated,
    onMounted,
    onUnmounted,
    ref,
    watch,
  } from 'vue';
  import { useRouter, onBeforeRouteLeave } from 'vue-router';
  import { throttle } from 'lodash';
  import productListV2 from '@/views/product/components/productListV2.vue';
  import { FeedItem, FeedsAPI, FeedsParams, ProductItem } from '@/api/feeds';
  import { useUserStore } from '@/store/user';
  import { AiAPI } from '@/api/ai';
  import { useLoginModal } from '@/composables/useLoginModal';
  const router = useRouter();
  const userStore = useUserStore();
  const isLoggedIn = computed(() => userStore.isAuthenticated);
  const userInfo = computed(() => userStore.user);
  const keyWord = ref<string>('');
  const loadStatus = ref<boolean>(false);
  const loadMoreLoading = ref(false);
  const hasMore = ref<boolean>(true);
  const customizationList = ref<any>([]);
  const products = ref<ProductItem[]>([]);
  const isActivated = ref(false);
  const isReturningFromOtherPage = ref(false);
  const savedScrollPosition = ref(0);
  const loading = ref<boolean>(false);
  const start = ref(0);
  const isDataLoaded = ref(false);
  const searchLoading = ref(false);
  const isFirstMount = ref(true);
  const search_text = ref<any>('');
  const searchTimeout = ref<number | any>(null);
  // 处理页面加载数据中就点击进入作品详情，瀑布流获取不到页面高度，在作品详情页返回图片堆叠到一起
  const isLeavePageLoadingMore = ref<boolean>(false);
  // 定义组件名称，用于keep-alive缓存
  defineOptions({
    name: 'product',
  });
  // 监听用户登录状态变化
  watch(isLoggedIn, (newValue, oldValue) => {
    console.log('用户登录状态变化:', { newValue, oldValue });
    // 当登录状态发生变化时，重置数据并重新加载
    if (newValue !== oldValue && newValue) {
      console.log('登录状态变化，重新加载数据');
      start.value = 0;
      products.value = [];
      isDataLoaded.value = false;
      loadProducts(false, true);
      getGenProductTemplates();
    }
  });

  onMounted(() => {
    // 设置激活状态
    isActivated.value = true;
    // 首次加载数据
    loadProducts();
    getGenProductTemplates();
    window.addEventListener('scroll', throttleHandleScroll);
  });

  // 路由离开前保存滚动位置
  onBeforeRouteLeave((to: any, from: any, next: any) => {
    console.log('路由离开前保存滚动位置');
    // 数据加载更多时候就离开页面
    if (loadMoreLoading.value) {
      isLeavePageLoadingMore.value = true;
    }
    saveScrollPosition();
    next();
  });

  // 保存滚动位置
  const saveScrollPosition = () => {
    // 使用nextTick确保DOM更新完成后再保存
    nextTick(() => {
      savedScrollPosition.value = window.pageYOffset || document.documentElement.scrollTop;
    });
  };

  // 获取product模型列表
  const getGenProductTemplates = async () => {
    const { code, data } = await AiAPI.genProductTemplates();
    if (code === 200) {
      customizationList.value = data || [];
    }
  };

  // 滚动监听函数（节流处理）
  const handleScroll = () => {
    // 如果组件刚激活，延迟处理滚动事件
    if (!isActivated.value) {
      return;
    }
    // 如果是从其他页面返回，禁用滚动加载
    if (isReturningFromOtherPage.value) {
      console.log('从其他页面返回，禁用滚动加载');
      return;
    }
    // 未登录用户禁用触底加载
    if (!isLoggedIn.value || !userInfo.value) {
      console.log('未登录用户，禁用滚动触底加载');
      return;
    }
    // 如果正在加载或没有更多数据，则不处理滚动
    if (loadMoreLoading.value || !hasMore.value) {
      return;
    }
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    const windowHeight = window.innerHeight;
    const documentHeight = document.documentElement.scrollHeight;

    // 当滚动到距离底部100px时触发加载
    if (scrollTop + windowHeight >= documentHeight - 100) {
      loadMore();
    }
  };

  const throttleHandleScroll: any = throttle(handleScroll, 300);

  // 触底加载更多数据
  const loadMore = async () => {
    if (loadMoreLoading.value || !hasMore.value || loading.value) return;
    // 只有登录用户才能触底加载更多
    if (!isLoggedIn.value || !userInfo.value) {
      console.log('未登录用户，禁用触底加载');
      return;
    }

    // 更新start值以获取下一页数据
    start.value = products.value.length;

    await loadProducts(true);
  };

  // 检查是否已加载数据
  const hasData = () => {
    return isDataLoaded.value && products.value.length > 0;
  };

  // 获取产品数据
  const loadProducts = async (isLoadMore = false, forceRefresh = false) => {
    // 如果是加载更多，直接执行
    if (isLoadMore) {
      await fetchProducts(isLoadMore);
      return;
    }

    // 检查是否已有数据且不需要强制刷新
    if (!forceRefresh && hasData()) {
      console.log('使用缓存数据，跳过接口调用');
      return;
    }

    await fetchProducts(isLoadMore);
  };

  // 实际的数据获取函数
  const fetchProducts = async (isLoadMore = false) => {
    try {
      if (isLoadMore) {
        loadMoreLoading.value = true;
      } else {
        loading.value = true;
      }
      const params: FeedsParams = {
        start: start.value,
        size: 30,
        search_text: search_text.value.trim() || undefined,
      };

      // 未登录用户限制数据量，不启用分页
      if (!isLoggedIn.value || !userInfo.value) {
        params.size = 20; // 未登录用户只加载20条数据
        console.log('未登录用户，限制数据量:', params.size);
      }
      const response = (await FeedsAPI.getProducts(params)) || {};
      // 处理页面加载数据中就点击进入作品详情，瀑布流获取不到页面高度，在作品详情页返回图片堆叠到一起
      if (isLeavePageLoadingMore.value) {
        loading.value = false;
        searchLoading.value = false;
        loadMoreLoading.value = false;
        return;
      }

      if (isLoadMore) {
        // 追加数据
        products.value = [...products.value, ...response.data.products];
      } else {
        // 替换数据
        products.value = response.data.products;
      }

      start.value = response.data.next_start;

      // 检查是否还有更多数据
      // 未登录用户禁用分页
      if (!isLoggedIn.value || !userInfo.value) {
        hasMore.value = false; // 未登录用户禁用分页
        console.log('未登录用户，禁用分页功能');
      } else {
        hasMore.value = response.data.has_more;
      }

      // 更新数据加载状态
      isDataLoaded.value = true;

      console.log('加载产品数据成功:', response);
    } catch (error) {
      console.error('加载产品数据失败:', error);
    } finally {
      loading.value = false;
      searchLoading.value = false;
      loadMoreLoading.value = false;
    }
  };

  // 防抖搜索功能
  const debouncedSearch = () => {
    if (searchTimeout.value) {
      clearTimeout(searchTimeout.value);
    }

    searchTimeout.value = setTimeout(() => {
      if (search_text.value.trim()) {
        searchLoading.value = true;
        start.value = 0; // 搜索时重置到第一页
        products.value = [];
        // 清除缓存，强制刷新
        isDataLoaded.value = false;
        loadProducts(false, true);
      } else {
        // 如果搜索框为空，重新加载默认数据
        start.value = 0;
        // 清除缓存，强制刷新
        isDataLoaded.value = false;
        loadProducts(false, true);
      }
    }, 500); // 500ms 防抖延迟
  };

  const goDetail = (item: any) => {
    if (!isLoggedIn.value || !userInfo.value) {
      const { showModal } = useLoginModal();
      showModal();
      return;
    }
    router.push({
      path: '/productDetail',
      query: {
        product_id: item?.product_id,
        template_id: item?.template_id,
        product_url: item?.product_url,
      },
    });
  };

  // 恢复滚动位置（无动画）
  const restoreScrollPosition = () => {
    if (savedScrollPosition.value > 0) {
      // 使用nextTick确保DOM渲染完成后再恢复
      nextTick(() => {
        // 使用scrollTo的behavior: 'instant'来避免滚动动画
        window.scrollTo({
          top: savedScrollPosition.value,
          left: 0,
          behavior: 'instant',
        });
        console.log('恢复滚动位置:', savedScrollPosition.value);
      });
    }
  };
  // 组件被激活时（从缓存中恢复）
  onActivated(() => {
    console.log('首页组件被激活');

    // 如果是首次挂载，跳过处理（onMounted已经处理了）
    if (isFirstMount.value) {
      console.log('首次挂载，跳过onActivated处理');
      // 标记首次挂载完成
      isFirstMount.value = false;
      return;
    }

    // 重新添加滚动监听
    window.addEventListener('scroll', throttleHandleScroll);

    // 延迟恢复滚动位置，确保DOM完全渲染
    setTimeout(() => {
      restoreScrollPosition();
    }, 100); // 100ms延迟

    // 延迟激活滚动处理，避免立即触发
    setTimeout(() => {
      isActivated.value = true;
    }, 500); // 500ms延迟

    // 延迟重置返回标志，允许正常滚动加载
    setTimeout(() => {
      isReturningFromOtherPage.value = false;
      console.log('重置返回标志，允许正常滚动加载');
    }, 1000); // 1秒后允许正常滚动加载

    if (isLeavePageLoadingMore.value) {
      loadMore();
    } else if (hasData()) {
      // 检查是否已有数据，如果有则跳过加载
      console.log('使用缓存数据，跳过接口调用');
    } else {
      console.log('无缓存数据，重新加载');
      loadProducts();
    }
    isLeavePageLoadingMore.value = false;
  });

  // 组件被停用时（离开页面）
  onDeactivated(() => {
    console.log('首页组件被停用，离开页面');

    // 标记为从其他页面返回
    isReturningFromOtherPage.value = true;
    console.log('设置返回标志，下次激活时将禁用滚动加载');

    // 移除滚动监听
    window.removeEventListener('scroll', throttleHandleScroll);
  });

  // 组件卸载时清理事件监听
  onUnmounted(() => {
    window.removeEventListener('scroll', throttleHandleScroll);
    if (searchTimeout.value) {
      clearTimeout(searchTimeout.value);
    }
  });
</script>

<style scoped lang="scss">
  .product_container {
    width: 100%;
    height: 100%;
    .content {
      background: #f8f8f8;
      height: 100%;
      padding: 16px 0 16px 0;
    }

    .pro_item_view {
      padding-right: 16px;
      padding-bottom: 32px;
      .pro_img_view {
        width: 406px;
        height: 406px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .pro_img {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }
    .cus_item_view {
      flex-shrink: 0;
      width: 33%;
      border-radius: 6px;
      margin-right: 16px;
      overflow: hidden;
      max-height: 320px;
      max-width: 560px;
      cursor: pointer;
      position: relative;
      .name {
        position: absolute;
        bottom: 0;
        left: 50%;
        width: 100%;
        padding: 16px 0;
        display: flex;
        align-items: center;
        justify-content: center;
        transform: translate(-50%, 0);
        color: var(---0, #fff);
        font-family: 'Inter Tight';
        font-size: 20px;
        font-style: normal;
        font-weight: 500;
        line-height: normal;
        background: linear-gradient(180deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.6) 100%);
      }
    }
    .cus_item_img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    .cus_img_list {
      display: flex; /* 弹性布局 */
      flex-direction: row;
      flex-wrap: nowrap;
      overflow-x: auto;
      /* 防止内容溢出容器高度（可选） */
      overflow-y: hidden;
      /* 隐藏滚动条的通用设置 */
      -ms-overflow-style: none; /* 针对 IE 和 Edge */
      scrollbar-width: none; /* 针对 Firefox */
    }
    .cus_img_list::-webkit-scrollbar {
      height: 0; /* 横向滚动条高度设为 0 */
      width: 0; /* 可选：若有纵向滚动条也隐藏 */
    }
    .title {
      color: var(---9, #222);

      font-size: 20px;
      font-style: normal;
      font-weight: 600;
      line-height: normal;
    }
    .color_222 {
      color: #222;
    }
    .search_view {
      background: #fff;
      padding: 16px 24px;
    }
    .el-input {
      --el-input-text-color: #7a7a7a;
      --el-input-border: var(--el-border);
      --el-input-hover-border: var(--el-border-color-hover);
      --el-input-focus-border: var(--el-color-primary);
      --el-input-transparent-border: 0 0 0 1px transparent inset;
      --el-input-border-color: #ededed;
      --el-input-border-radius: 8px;
      --el-input-bg-color: #ededed;
      --el-input-icon-color: var(--el-text-color-placeholder);
      --el-input-placeholder-color: var(--el-text-color-placeholder);
      --el-input-hover-border-color: var(--el-border-color-hover);
      --el-input-clear-hover-color: var(--el-text-color-secondary);
      --el-input-focus-border-color: #7a7a7a;
      --el-input-width: 100%;
      --el-input-height: 48px;
      box-sizing: border-box;
      display: inline-flex;
      font-size: 15px;
      line-height: var(--el-input-height);
      position: relative;
      vertical-align: middle;
      width: var(--el-input-width);
    }
  }
</style>
